
// base64位转换成File类型
export function base64ConvertFile (urlData:string, fileName: string) {
	// 64转file
	if (typeof urlData !== 'string') {
		console.warn('urlData不是字符串');
		return;
	}
	const arr = urlData.split(',');
	const types = arr[0].match(/:(.*?);/)
	const type = types ? types[1] : '';
	const fileExt = type.split('/')[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], fileName + '.' + fileExt, {
		type: type,
	});
};

/**
 * 
 * @param src 选中的图片，input type=file选中的文件
 * @param width 压缩的宽度
 * @param height 压缩的高度
 * @param quality 
 * @returns 
 */
export function compressImage(src:File, width: number, height: number, quality: number) {
    return new Promise((resolve)=> {
          const img = new Image();
          img.src = URL.createObjectURL(src);
          img.onload = function() {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              if (img.width > img.height) {
                  height = img.height * (width / img.width);
              } else {
                  width = img.width * (height / img.height);
              }
              canvas.width = width;
              canvas.height = height;
              ctx?.drawImage(img, 0, 0,  img.width, img.height, 0, 0, width, height);
              const dataUrl: string = canvas.toDataURL(src.type, quality);
              return base64ConvertFile(dataUrl, src.name)
          };
    }) 
  }